import { Hono } from 'hono'

interface Metrics {
  requests: {
    total: number
    success: number
    error: number
    avgResponseTime: number
  }
  plugins: {
    total: number
    enabled: number
    errors: number
  }
  system: {
    uptime: number
    memory: NodeJS.MemoryUsage
    cpu: number
  }
}

class MetricsCollector {
  private metrics: Metrics = {
    requests: { total: 0, success: 0, error: 0, avgResponseTime: 0 },
    plugins: { total: 0, enabled: 0, errors: 0 },
    system: { uptime: 0, memory: process.memoryUsage(), cpu: 0 }
  }

  private responseTimes: number[] = []

  recordRequest(responseTime: number, success: boolean) {
    this.metrics.requests.total++
    
    if (success) {
      this.metrics.requests.success++
    } else {
      this.metrics.requests.error++
    }

    this.responseTimes.push(responseTime)
    
    // 保持最近1000个响应时间
    if (this.responseTimes.length > 1000) {
      this.responseTimes.shift()
    }

    // 计算平均响应时间
    this.metrics.requests.avgResponseTime = 
      this.responseTimes.reduce((a, b) => a + b, 0) / this.responseTimes.length
  }

  recordPluginMetrics(total: number, enabled: number, errors: number) {
    this.metrics.plugins = { total, enabled, errors }
  }

  updateSystemMetrics() {
    this.metrics.system = {
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      cpu: process.cpuUsage().user / 1000000 // 转换为秒
    }
  }

  getMetrics(): Metrics {
    this.updateSystemMetrics()
    return { ...this.metrics }
  }

  // Prometheus 格式输出
  getPrometheusMetrics(): string {
    this.updateSystemMetrics()
    
    return `
# HELP baihu_requests_total Total number of requests
# TYPE baihu_requests_total counter
baihu_requests_total ${this.metrics.requests.total}

# HELP baihu_requests_success_total Total number of successful requests
# TYPE baihu_requests_success_total counter
baihu_requests_success_total ${this.metrics.requests.success}

# HELP baihu_requests_error_total Total number of failed requests
# TYPE baihu_requests_error_total counter
baihu_requests_error_total ${this.metrics.requests.error}

# HELP baihu_response_time_avg Average response time in milliseconds
# TYPE baihu_response_time_avg gauge
baihu_response_time_avg ${this.metrics.requests.avgResponseTime}

# HELP baihu_plugins_total Total number of plugins
# TYPE baihu_plugins_total gauge
baihu_plugins_total ${this.metrics.plugins.total}

# HELP baihu_plugins_enabled Number of enabled plugins
# TYPE baihu_plugins_enabled gauge
baihu_plugins_enabled ${this.metrics.plugins.enabled}

# HELP baihu_system_uptime System uptime in seconds
# TYPE baihu_system_uptime gauge
baihu_system_uptime ${this.metrics.system.uptime}

# HELP baihu_memory_usage Memory usage in bytes
# TYPE baihu_memory_usage gauge
baihu_memory_usage{type="rss"} ${this.metrics.system.memory.rss}
baihu_memory_usage{type="heapUsed"} ${this.metrics.system.memory.heapUsed}
baihu_memory_usage{type="heapTotal"} ${this.metrics.system.memory.heapTotal}
    `.trim()
  }
}

export const metricsCollector = new MetricsCollector()

// 中间件
export function metricsMiddleware() {
  return async (c: any, next: any) => {
    const start = Date.now()
    
    try {
      await next()
      const responseTime = Date.now() - start
      metricsCollector.recordRequest(responseTime, c.res.status < 400)
    } catch (error) {
      const responseTime = Date.now() - start
      metricsCollector.recordRequest(responseTime, false)
      throw error
    }
  }
}
